<template>
  <el-dialog :visible="visible" center :show-close="false" width="650px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ title }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>
    <el-form class="pl30 pr30" :model="form" ref="form" label-width="80px">
      <el-form-item
        :label="$t('sys.shift_name')"
        prop="name"
        :rules="[
          { required: true, message: $t('sys.shift_name_not_null'), trigger: 'change' },
        ]"
      >
        <el-input
          style="width: 100%"
          v-model="form.name"
          :maxlength="32"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.shift_time')"
        prop="shiftTime"
        :rules="[{ validator: validateShiftTime, trigger: 'change' }]"
      >
        <div style="display: flex">
          <el-form-item
            style="width: calc(50% - 20px)"
            prop="startTime"
            label-width="0px"
            :rules="[
              {
                required: true,
                message: $t('sys.shift_start_time_not_null'),
                trigger: 'change',
              },
            ]"
          >
            <el-time-picker
              v-model="form.startTime"
              format="HH:mm"
              value-format="HH:mm"
              :placeholder="$t('sys.start_time')"
              @change="$refs.form.validateField('shiftTime')"
            >
            </el-time-picker>
          </el-form-item>
          <span style="width: 20px; text-align: center">-</span>
          <el-form-item
            :rules="[
              {
                required: true,
                message: $t('sys.shift_end_time_not_null'),
                trigger: 'change',
              },
            ]"
            style="width: calc(50% - 20px)"
            prop="endTime"
            label-width="0px"
          >
            <el-time-picker
              v-model="form.endTime"
              format="HH:mm"
              value-format="HH:mm"
              :placeholder="$t('sys.end_time')"
              @change="$refs.form.validateField('shiftTime')"
            >
            </el-time-picker>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item :label="$t('sys.down_time')">
        <el-button type="text" @click="handleAddplanTimes">{{$t('sys.add')}}</el-button>

        <div
          style="display: flex"
          v-for="(item, index) in form.planTimes"
          :key="index"
        >
          <el-form-item
            style="width: 20%; margin-right: 10px"
            label=""
            label-width="0px"
            :prop="'planTimes.' + index + '.planId'"
            :rules="[
              { required: true, message: $t('sys.type_not_null'), trigger: 'change' },
            ]"
          >
            <el-select v-model="item.planId">
              <el-option
                v-for="type in planTypes"
                :key="type.id"
                :value="type.id"
                :label="type.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            style="width: calc(80% - 20px)"
            :prop="'planTime_' + index"
            :rules="[
              {
                validator: handleplanTimesValidate,
                trigger: 'change',
              },
            ]"
          >
            <el-form-item
              style="width: calc(50% - 10px); display: inline-block"
              :prop="'planTimes.' + index + '.startTime'"
              label-width="0px"
              :rules="[
                {
                  required: true,
                  message: $t('sys.start_time_not_null'),
                  trigger: 'change',
                },
              ]"
            >
              <el-time-picker
                style="margin-bottom: 0px"
                v-model="item.startTime"
                format="HH:mm"
                value-format="HH:mm"
                :placeholder="$t('sys.start_time')"
                @change="$refs.form.validateField('planTime_' + index)"
              >
              </el-time-picker>
            </el-form-item>
            <span style="width: 20px; text-align: center; display: inline-block"
              >-</span
            >
            <el-form-item
              style="width: calc(50% - 10px); display: inline-block"
              :prop="'planTimes.' + index + '.endTime'"
              label-width="0px"
              :rules="[
                {
                  required: true,
                  message: $t('sys.end_time_not_null'),
                  trigger: 'change',
                },
              ]"
            >
              <el-time-picker
                v-model="item.endTime"
                format="HH:mm"
                value-format="HH:mm"
                :placeholder="$t('sys.end_time')"
                @change="$refs.form.validateField('planTime_' + index)"
              >
              </el-time-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label-width="10px">
            <el-button
              v-if="form.planTimes.length > 0"
              type="text"
              @click="handleDelPlanTimeList(item, index)"
            >
              <i class="el-icon-delete" />
            </el-button>
          </el-form-item>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button @click="handleCancel">{{$t('sys.cancel')}}</el-button>
      <el-button :loading="confirmLoading" type="primary" @click="handleSubmit"
        >{{$t('sys.confirm')}}</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { postHmshifts,putHmshifts,getHmshiftsValidatefield } from '@/apis/paas/HmShiftsController.js'
import { isTimeContain, isTimeCross } from "@/utils/util";

export default {
  name: "ShiftFrom",

  props: {
    shifts: {
      type: Array,
      default: () => [],
    },
  },
  components: {},
  data() {
    return {
      visible: false,
      confirmLoading: false,
      form: {
        timeRange: [],
        planTimes: [],
      },
      title: "",
    };
  },
  computed: {
    planTypes() {
      // return this.$store.getters.planTypes;
      return [{ id: 1, name: this.$t("sys.rest") }];
    },
  },
  created() {},
  methods: {
    init() {
      this.form = {
        id: 0,
        name: "",
        timeRange: [],
        startTime: undefined,
        endTime: undefined,
        planTimes: [],
      };
    },

    add() {
      this.visible = true;
      this.type = "ADD";
      this.title = this.$t("sys.new_shift");
      this.init();
    },

    edit(record) {
      this.visible = true;
      this.type = "EDIT";
      this.title = this.$t("sys.edit_shift");
      const { id, name, startTime, endTime, planTimes } = record;
      const oplanTimes = planTimes.map((item) => {
        const oItem = Object.assign({}, item);
        oItem.deleted = 0;
        oItem.planId = 1;
        return oItem;
      });
      this.form = {
        id: id,
        name: name,
        startTime: startTime || undefined,
        endTime: endTime || undefined,
        planTimes: oplanTimes,
      };
    },
    validateShiftTime(rule, value, callback) {
      if (!this.form.startTime || !this.form.endTime) {
        callback();
      } else {
        const params = {
          fieldName: "shiftTimeField",
          field: "shiftTimeField",
          key: "shiftTimeField",
          value: this.form.startTime + "-" + this.form.endTime,
          id: this.form.id || 0,
          userId: this.$store.getters.getUserVal.id,
        };
        getHmshiftsValidatefield(params)
          .then((res) => {
            callback();
          })
          .catch((e) => {
            callback(e.message);
          });
      }
    },
    handleplanTimesValidate(rule, value, callback) {
      const field = rule.field;
      const filedInfo = field.split("_");
      const currentIndex = filedInfo[1];
      const { startTime, endTime } = this.form;
      const planTimes = this.form.planTimes;
      // 没有停机时间 or 班次时间不完整
      if (planTimes.length === 0 || !startTime || !endTime) {
        callback();
      }
      const rangeFrom = startTime;
      const rangeTo = endTime;
      const range = {
        from: rangeFrom,
        to: rangeTo,
      };
      for (let index = 0; index < planTimes.length; index++) {
        // 停机时间不完整
        if (index != currentIndex) continue;
        if (!planTimes[index].startTime || !planTimes[index].endTime) {
          // callback(new Error(`停机时间不能为空`))
          break;
        }
        const periodFrom = planTimes[index].startTime;
        const periodTo = planTimes[index].endTime;
        const period = {
          from: periodFrom,
          to: periodTo,
        };
        // 当前停机时间是否在班次时间内
        if (!isTimeContain(range, period)) {
          callback(
            new Error(
              this.$t("sys.downtime_not_outside_shift_not_overlap_with_other_downtime_within_shift")
            )
          );
          break;
        }
        // 当前停机时间是否跟其他停机时间交叉（只对比前面的数据）
        let isError = false;
        for (let j = 0; j < index; j++) {
          const jRangeFrom = planTimes[j].startTime;
          const jRangeTo = planTimes[j].endTime;
          const jRange = {
            from: jRangeFrom,
            to: jRangeTo,
          };
          if (isTimeCross(jRange, period)) {
            isError = true;
            callback(
              new Error(
                this.$t("sys.downtime_not_outside_shift_not_overlap_with_other_downtime_within_shift")
              )
            );
            break;
          }
        }
        if (isError) {
          break;
        }
      }
      callback();
    },

    // handlePlanTimeListChange (prop, index, time) {
    //   this.record.planTimes[index][prop] = time
    //   const { startTime, endTime } = this.record.planTimes[index]
    //   if (!startTime || !endTime) {
    //
    //   }
    //   // this.form.validateFields(['planTimesField'], { force: true }, () => {
    //   // })
    // },
    handleAddplanTimes() {
      if (this.planTypes.length === 0) {
        this.$notify({
          title: this.$t("sys.operation_failed"),
          message: this.$t("sys.set_planned_downtime_type"),
          type: "warning",
        });
      }
      const defaultId = this.planTypes[0].id;
      const defaultName = this.planTypes[0].name;
      this.form.planTimes.push({
        planId: defaultId,
        startTime: undefined,
        endTime: undefined,
        name: defaultName,
      });
    },
    handleAddplanTimes1() {
      if (this.planTypes.length === 0) {
        this.$notify({
          title: this.$t("sys.operation_failed"),
          message: this.$t("sys.set_planned_downtime_type"),
          type: "warning",
        });
        return;
      }
      // 取计划停机类型第一条作为默认值
      const defaultId = this.planTypes[0].id;
      const defaultName = this.planTypes[0].name;
      this.record.planTimes.push({
        planId: defaultId,
        startTime: undefined,
        endTime: undefined,
        deleted: 0,
        name: defaultName,
      });
    },

    handleDelPlanTimeList(item, index) {
      this.form.planTimes.splice(index, 1);
    },

    async handleSubmit() {
      try {
        await this.$refs.form.validate();
        const { id, name, startTime, endTime, planTimes } = this.form;
        const userId = this.$store.getters.getUserVal.id;
        let params = {};
        let request = null;
        if (this.type === "ADD") {
          params = { name, startTime, endTime, planTimes: planTimes, userId };
          request = postHmshifts;
        } else {
          params = {
            id,
            name,
            startTime,
            endTime,
            planTimes: planTimes,
            userId,
          };
          request = putHmshifts;
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }
        this.confirmLoading = true;
        request(params)
          .then((res) => {
            this.handleCancel();
            this.$emit("ok");
          })
          .finally(() => {
            this.confirmLoading = false;
          });
      } catch (error) {
        console.log(error);
      }
    },

    handleCancel() {
      this.visible = false;
      this.$refs.form.resetFields();
      this.init();
    },
  },
};
</script>

<style lang="scss" scoped>
.hidden {
  display: none;
}

.el-date-editor.el-input {
  width: 100%;
}
</style>
